<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" class="form-container">
      <input type="hidden"  name="courseId" v-model="postForm.courseId" />
      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.formStatus">
        <el-row type="flex" justify="space-between">
          <el-col :span="2">
            <el-button v-loading="loading" type="primary" @click="back" class="">
              返回
            </el-button>
          </el-col>
          <el-col :span="16" v-if="postForm.parentName" style="text-align: left;padding-left: 15px;;">
            <el-tag  type="info">上级</el-tag>
            <el-link type="warning"  disabled >{{postForm.parentName}}</el-link>
          </el-col>
          <el-col :span="6">
            <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
              保存
            </el-button>
            <el-button v-loading="loading" type="warning" @click="draftForm">
              草稿
            </el-button>
          </el-col>
        </el-row>
      </sticky>
      <div class="createPost-main-container">
        <!-- <aside>
          Creating and editing pages
          <a href=""  target="_blank">Document</a>
        </aside> -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item style="margin-bottom: 30px;" prop="name">
              <MDinput v-model="postForm.name" :maxlength="100" required>
                 章节标题
              </MDinput>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" label-width="70px" label="简介">
              <el-input v-model="postForm.intro" :rows="1" type="textarea" class="article-textarea" autosize placeholder="请输入简介" />
              <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}字</span>
            </el-form-item>
           <!-- <el-form-item label-width="80px" label="开始时间:" prop="begin_time" class="postInfo-container-item">
              <el-date-picker v-model="postForm.begin_time" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="请选择" />
            </el-form-item> -->
          </el-col>
        </el-row>
        <el-form-item  prop="detail" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.detail" :height="300" @saveServer="saveContentServer" menubar=""/>
        </el-form-item>
        <el-form-item label="章节封面" >
          <el-upload :limit="imgUploadLimit" :action="imgUploadUrl" :file-list="fileList"
            list-type="picture-card"
            :headers = "headers"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleUploadRemove"
            :on-success="handleUploadSuccess"
            :on-exceed="handleUploadExceed"
            :on-error="handleUploadError" >
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">1、只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <el-dialog :visible.sync="uploadDialogVisible">
            <img width="100%" :src="uploadDialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
       <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="启用" prop="enable">
             <el-switch  v-model="postForm.enable"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row> -->
      </div>
    </el-form>
  </div>
</template>

<script>
  import Tinymce from '@/components/Tinymce'
  import Upload from '@/components/Upload/SingleImage3'
  import MDinput from '@/components/MDinput'
  import { getQueryObject} from '@/utils'
  import Sticky from '@/components/Sticky' // 粘性header组件
  import API from '@/api/chapter'
  import imageAPI from '@/api/image'
  import { getToken } from '@/utils/auth'
  const defaultForm = {
    formStatus:"published",
    id: 0,
    name: '',
    pic: '',
    parentId:null,
    parentName:null,
    intro: '',
    detail:"",
    courseId:null
  }

  export default {
    name: 'chapterAdd',
    components: {
      Tinymce,
      MDinput,
      Upload,
      Sticky
    },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      const validateRequire = (rule, value, callback) => {
        if (value === '') {
          this.$message({
            message: rule.label + '为必传项',
            type: 'error'
          })
          callback(new Error(rule.label + '为必传项'))
        } else {
          callback()
        }
      }

      return {
        postForm: Object.assign({}, defaultForm),
        loading: false,
        rules: {
          name: [{
            validator: validateRequire,
            label: '章节标题'
          }]
        },
        tempRoute: {},
        submitBack:true,
        fileList:[],//图片上传相关
        uploadDialogImageUrl: '',
        uploadDialogVisible: false,
        imgUploadLimit:1,
        imgUploadUrl:this.$imgServer+"/api/imgupload",
        headers:{
          Authorization: "Bearer "+ getToken()  //从cookie里获取token，并赋值  Authorization ，而不是token
        }
      }
    },
    computed: {
      contentShortLength() {
        return this.postForm.intro.length
      },
      displayTime: {
        // set and get is useful when the data
        // returned by the back end api is different from the front end
        // back end return => "2013-06-25 06:59:25"
        // front end need timestamp => 1372114765000
        get() {
          return (+new Date(this.postForm.display_time))
        },
        set(val) {
          this.postForm.display_time = new Date(val)
        }
      }
    },
    created() {
      var queryobj=getQueryObject()
      this.postForm.courseId=queryobj.courseid?parseInt(queryobj.courseid):null;
      this.postForm.parentId=queryobj.parentId?parseInt(queryobj.parentId):null;
      this.postForm.parentName=queryobj.parentName
      const id = queryobj.id
      id&& this.fetchOne(id);
      // Why need to make a copy of this.$route here?
      // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
      // https://github.com/PanJiaChen/vue-element-admin/issues/1221
      this.tempRoute = Object.assign({}, this.$route)
    },
    methods: {
      fetchOne(id) {
        API.fetchOne(id).then(response => {
          this.postForm = response.data
          response.data.pic&&( this.fileList=[{name: response.data.pic, url:this.$imgServer+response.data.pic }])
          // set tagsview title
          this.setTagsViewTitle()
          // set page title
          this.setPageTitle()
        }).catch(err => {
          console.log(err)
        })
      },
      setTagsViewTitle() {
        const title = '章节修改'
        const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.name}` })
        this.$store.dispatch('tagsView/updateVisitedView', route)
      },
      setPageTitle() {
        const title = '章节修改'
        document.title = `${title} - ${this.postForm.name}`
      },
      back() {
        this.$router.push({path:'/admin/chapter',query:{courseid:this.postForm.courseId}})
        // this.$router.go(-1)
      },
      submitForm() {
        this.submitBack=true
        this. saveForm()
      },
      saveForm() {
        //console.log(this.postForm)
        if(!this.postForm.courseId){
          this.$message({
            message: '请选择要添加的课程',
            type: 'warning'
          })
          return}
        this.$refs.postForm.validate(valid => {
          if (valid) {
            this.loading = true
            if(this.postForm.id){ //id存在表示修改
              API.update(this.postForm).then(() => {
                this.$notify({
                  title: '提交成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 1000
                })
              })
            }else{
                API.add(this.postForm).then(() => {
                  this.$notify({
                    title: '提交成功',
                    message: '发布成功',
                    type: 'success',
                    duration: 1000
                   })
                })
            }
            this.submitBack&&this.back()
            this.loading = false
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
     draftForm() {
        if (this.postForm.detail.length === 0 || this.postForm.name.length === 0) {
          this.$message({
            message: '请填写必要的标题和内容',
            type: 'warning'
          })
          return
        }
        this.$message({
          message: '保存成功',
          type: 'success',
          showClose: true,
          duration: 1000
        })
        this.postForm.formStatus = 'draft'
      },
     saveContentServer(){
        this.submitBack=false
        this.saveForm()
     },
     handleUploadRemove(file, fileList) {
        //console.log(file, fileList);
        if(file.id){
          imageAPI.delete(file.id)
        }else{
          var params=param2Obj(file.url)
          if(params.id){
            imageAPI.delete(params.id)
          }else{
            this.$message.warning("未能从数据库删除此图片，未指定id或者此图片正在使用");
          }
        }
        this.postForm.pic=''
     },
     handleUploadSuccess(response, file, fileList) {
        //console.log(file, fileList);
        if(!response.status){
           this.$message.error(response.msg);
           fileList.pop()
           return
        }
        file.id=response.data.id
        this.postForm.pic=response.data.path+"?id="+ file.id
     },
     handlePictureCardPreview(file) {
       this.uploadDialogImageUrl = file.url;
       this.uploadDialogVisible = true;
     },
     handleUploadExceed(files, fileList){
       this.$message.warning(`当前限制选择 ${this.imgUploadLimit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
     },
     handleUploadError(err, file, fileList){
        this.$message.error(`上传文件${file.name}失败`+err);
     }
    }
  }
</script>

<style lang="scss" scoped>
  @import "~@/styles/mixin.scss";

  .createPost-container {
    position: relative;

    .createPost-main-container {
      padding: 40px 45px 20px 50px;

      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;

        .postInfo-container-item {
          float: left;
        }
      }
    }

    .word-counter {
      width: 40px;
      position: absolute;
      right: 10px;
      top: 0px;
    }
  }

  .chapter-textarea /deep/ {
    textarea {
      padding-right: 40px;
      resize: none;
      border: none;
      border-radius: 0px;
      border-bottom: 1px solid #bfcbd9;
    }
  }
</style>
